package org.sun.online.internal.common.advice;

import lombok.SneakyThrows;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;
import org.sun.online.internal.common.common.exception.OnlineTaxiBeseException;
import org.sun.online.internal.common.common.exception.code.ResponseCodeEnum;
import org.sun.online.internal.common.response.Response;
import org.sun.online.internal.common.trace.TraceIdUtils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @author sunhongmin
 * @date 2022/5/30 12:53
 * @description
 */
public class GlobalExceptionInterceptor implements HandlerExceptionResolver {

    @SneakyThrows
    @Override
    public ModelAndView resolveException(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler, Exception ex) {
        Map<String, Object> model = new HashMap<String, Object>();
        model.put("ex", ex);
        model.put("traceId",TraceIdUtils.getTraceId());
        if (ex instanceof OnlineTaxiBeseException) {
            Response<Object> fail = Response.fail(ResponseCodeEnum.CODE_INTERNAL_ERROR.getCode(), ex.getMessage(), null).setTraceId(TraceIdUtils.getTraceId());
            return parseResponseToModelAndView(fail);
        }

        ex.printStackTrace();
        return new ModelAndView("view-error", model);
    }

    private <T> ModelAndView parseResponseToModelAndView(Response<T> response) throws IllegalAccessException {
        Class<? extends Response> responseClass = response.getClass();
        Field[] declaredFields = responseClass.getDeclaredFields();
        ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
        for (Field field : declaredFields) {
            field.setAccessible(true);
            modelAndView.addObject(field.getName(),field.get(response));
        }
        return modelAndView;
    }
}
